<template>
  <div class="cesium-map-demo">
    <div ref="mapContainer" class="map-container"></div>
    <div class="toolbar">
      <button @click="addPoint">添加点</button>
      <button @click="flyToPoint">定位到点</button>
      <button @click="removePoint">移除点</button>
      <button @click="addMarker">添加Marker</button>
      <button @click="flyToMarker">定位到Marker</button>
      <button @click="removeMarker">移除Marker</button>
      <button @click="addPolyline">画线</button>
      <button @click="removePolyline">移除线</button>
      <button @click="addCircle">画圆</button>
      <button @click="removeCircle">移除圆</button>
      <button @click="addPolygon">画多边形</button>
      <button @click="removePolygon">移除多边形</button>
      <button @click="startDrawLine">鼠标画线</button>
      <button @click="startDrawCircle">鼠标画圆</button>
      <button @click="startDrawPolygon">鼠标画多边形</button>
      <button @click="addFence">添加围栏</button>
      <button @click="removeFence">移除围栏</button>
      <button @click="clearAllFences">清除所有围栏</button>
      <button @click="startDrawFence">鼠标绘制围栏</button>
      <button @click="startMeasureDistance">测量距离</button>
      <button @click="startMeasureArea">测量面积</button>
      <button @click="clearMeasure">清除测量</button>
      <button @click="addArc">画弧形</button>
      <button @click="startDrawArc">鼠标画弧形</button>
      <button @click="startMarkPoint">开始标记点</button>
      <button @click="stopMarkPoint">停止标记点</button>
      <button @click="clearMarkPoints">清除标记点</button>
    </div>
    <div v-if="measureResult" class="measure-result">{{ measureResult }}</div>
    <div v-if="fenceCount > 0" class="fence-info">当前围栏数量: {{ fenceCount }}</div>
    <!-- 属性弹窗 -->
    <div v-if="popupVisible" class="popup" :style="{ left: popupScreen.x + 'px', top: popupScreen.y + 'px' }" v-html="popupContent"></div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue';
import CesiumMap from '../utils/CesiumMap';

// 地图容器 DOM 引用
const mapContainer = ref(null);
// CesiumMap 实例
let cesiumMap = null;
// 各类实体引用
let pointEntity = null; // 单点实体
let markerEntity = null; // marker实体
let polylineEntity = null; // 折线实体
let circleEntity = null; // 圆实体
let polygonEntity = null; // 多边形实体
let drawingEntity = null; // 交互绘制中的临时实体
let drawingPositions = []; // 交互绘制中的点数组
let drawing = false; // 是否处于交互绘制状态
let drawType = ''; // 当前交互绘制类型
let fenceEntity = null; // 围栏实体
let fenceEntities = []; // 围栏实体数组，用于存储多个围栏
let drawPointEntities = []; // 交互绘制点的实体数组
// 测量相关
let measureType = ''; // 测量类型（distance/area）
let measurePositions = []; // 测量点数组
let measureEntity = null; // 测量临时实体
let measureResult = ref(''); // 测量结果文本
let measurePointEntities = []; // 测量点实体数组
// 弧形绘制相关
let arcDrawPoints = []; // 弧形交互点
let arcDrawEntity = null; // 弧形临时实体
let arcDrawPointEntities = []; // 弧形点实体数组
// 标记点相关
let markerPointEntities = []; // 标记点实体数组
let marking = false; // 是否处于标记点模式
// 属性弹窗相关
let popupVisible = ref(false);
let popupContent = ref('');
let popupScreen = ref({ x: 0, y: 0 });
let popupEnabled = ref(true); // 是否允许弹窗
let fenceCount = ref(0); // 围栏数量

onMounted(() => {
  // 初始化 CesiumMap 实例
  cesiumMap = new CesiumMap(mapContainer.value, {
    // 可自定义参数
  });
  // 注册实体点击事件，显示属性弹窗（仅允许时）
  cesiumMap.onEntityClick(({ entity, screenPosition }) => {
    if (!popupEnabled.value) return;
    // 只在点击marker（带billboard属性）时弹窗
    if (entity && entity.billboard && (entity.name || entity.description)) {
      popupContent.value = `<b>${entity.name || ''}</b><br>${entity.description || ''}`;
      popupScreen.value = { x: screenPosition.x, y: screenPosition.y };
      popupVisible.value = true;
    } else {
      popupVisible.value = false;
    }
  });
  // 注册地图点击事件，点击空白处关闭弹窗
  cesiumMap.viewer.screenSpaceEventHandler.setInputAction((movement) => {
    const picked = cesiumMap.viewer.scene.pick(movement.position);
    if (!picked || !picked.id) {
      popupVisible.value = false;
    }
  }, CesiumMap.ScreenSpaceEventType.LEFT_CLICK);
});

onBeforeUnmount(() => {
  // 销毁地图和清理交互
  cesiumMap && cesiumMap.destroy();
  clearDrawing();
});

/**
 * 添加一个普通点
 */
function addPoint() {
  if (pointEntity) return;
  pointEntity = cesiumMap.addEntity({
    position: CesiumMap.Cartesian3.fromDegrees(116.3913, 39.9075, 100),
    point: {
      pixelSize: 10,
      color: CesiumMap.Color.RED,
    },
    description: '北京',
  });
}

/**
 * 相机飞到点
 */
function flyToPoint() {
  if (pointEntity) {
    cesiumMap.flyTo(pointEntity);
  }
}

/**
 * 移除点
 */
function removePoint() {
  if (pointEntity) {
    cesiumMap.removeEntity(pointEntity);
    pointEntity = null;
  }
}

/**
 * 添加 marker
 */
function addMarker() {
  if (markerEntity) return;
  markerEntity = cesiumMap.addMarker({
    lon: 116.3974,
    lat: 39.9087,
    image: 'https://cdn.jsdelivr.net/gh/openlayers/ol3@master/examples/data/icon.png',
    width: 40,
    heightPx: 40,
    name: '天安门',
    description: '天安门广场',
  });
}

/**
 * 相机飞到 marker
 */
function flyToMarker() {
  if (markerEntity) {
    cesiumMap.flyTo(markerEntity);
  }
}

/**
 * 移除 marker
 */
function removeMarker() {
  if (markerEntity) {
    cesiumMap.removeEntity(markerEntity);
    markerEntity = null;
  }
}

/**
 * 添加折线
 */
function addPolyline() {
  if (polylineEntity) return;
  polylineEntity = cesiumMap.addPolyline({
    positions: [
      [116.3913, 39.9075],
      [116.3974, 39.9087],
      [116.4053, 39.9200],
    ],
    color: CesiumMap.Color.BLUE,
    width: 4,
    name: '示例线',
    description: '北京示例线',
  });
}

/**
 * 移除折线
 */
function removePolyline() {
  if (polylineEntity) {
    cesiumMap.removeEntity(polylineEntity);
    polylineEntity = null;
  }
}

/**
 * 添加圆
 */
function addCircle() {
  if (circleEntity) return;
  circleEntity = cesiumMap.addCircle({
    lon: 116.3913,
    lat: 39.9075,
    radius: 1000,
    color: CesiumMap.Color.GREEN.withAlpha(0.3),
    outlineColor: CesiumMap.Color.GREEN,
    outlineWidth: 2,
    name: '示例圆',
    description: '北京圆',
  });
}

/**
 * 移除圆
 */
function removeCircle() {
  if (circleEntity) {
    cesiumMap.removeEntity(circleEntity);
    circleEntity = null;
  }
}

/**
 * 添加多边形
 */
function addPolygon() {
  if (polygonEntity) return;
  polygonEntity = cesiumMap.addPolygon({
    positions: [
      [116.3913, 39.9075],
      [116.3974, 39.9087],
      [116.4053, 39.9200],
      [116.4000, 39.9300],
    ],
    color: CesiumMap.Color.YELLOW.withAlpha(0.4),
    outlineColor: CesiumMap.Color.YELLOW,
    outlineWidth: 2,
    name: '示例多边形',
    description: '北京多边形',
  });
}

/**
 * 移除多边形
 */
function removePolygon() {
  if (polygonEntity) {
    cesiumMap.removeEntity(polygonEntity);
    polygonEntity = null;
  }
}

function clearDrawing() {
  if (drawingEntity) {
    cesiumMap.removeEntity(drawingEntity);
    drawingEntity = null;
  }
  drawPointEntities.forEach(e => cesiumMap.removeEntity(e));
  drawPointEntities = [];
  drawingPositions = [];
  drawing = false;
  drawType = '';
  cesiumMap.removeScreenSpaceEventHandler(CesiumMap.ScreenSpaceEventType.LEFT_CLICK);
  cesiumMap.removeScreenSpaceEventHandler(CesiumMap.ScreenSpaceEventType.MOUSE_MOVE);
  cesiumMap.removeScreenSpaceEventHandler(CesiumMap.ScreenSpaceEventType.RIGHT_CLICK);
  popupEnabled.value = true;
}

function startDrawLine() {
  popupEnabled.value = false;
  clearDrawing();
  drawing = true;
  drawType = 'polyline';
  cesiumMap.addScreenSpaceEventHandler(CesiumMap.ScreenSpaceEventType.LEFT_CLICK, handleDrawClick);
  cesiumMap.addScreenSpaceEventHandler(CesiumMap.ScreenSpaceEventType.MOUSE_MOVE, handleDrawMove);
  cesiumMap.addScreenSpaceEventHandler(CesiumMap.ScreenSpaceEventType.RIGHT_CLICK, handleDrawEnd);
}

function startDrawCircle() {
  popupEnabled.value = false;
  clearDrawing();
  drawing = true;
  drawType = 'circle';
  cesiumMap.addScreenSpaceEventHandler(CesiumMap.ScreenSpaceEventType.LEFT_CLICK, handleDrawClick);
  cesiumMap.addScreenSpaceEventHandler(CesiumMap.ScreenSpaceEventType.MOUSE_MOVE, handleDrawMove);
  cesiumMap.addScreenSpaceEventHandler(CesiumMap.ScreenSpaceEventType.RIGHT_CLICK, handleDrawEnd);
}

function startDrawPolygon() {
  popupEnabled.value = false;
  clearDrawing();
  drawing = true;
  drawType = 'polygon';
  cesiumMap.addScreenSpaceEventHandler(CesiumMap.ScreenSpaceEventType.LEFT_CLICK, handleDrawClick);
  cesiumMap.addScreenSpaceEventHandler(CesiumMap.ScreenSpaceEventType.MOUSE_MOVE, handleDrawMove);
  cesiumMap.addScreenSpaceEventHandler(CesiumMap.ScreenSpaceEventType.RIGHT_CLICK, handleDrawEnd);
}

function addFence() {
  const newFence = cesiumMap.addFence({
    positions: [
      [116.3913, 39.9075],
      [116.3974, 39.9087],
      [116.4053, 39.9200],
      [116.4000, 39.9300],
    ],
    height: 200,
    color: CesiumMap.Color.CYAN.withAlpha(0.5),
    outlineColor: CesiumMap.Color.CYAN,
    outlineWidth: 2,
    name: '示例围栏',
    description: '北京围栏',
  });
  fenceEntities.push(newFence);
  // 保持向后兼容
  fenceEntity = newFence;
  fenceCount.value++;
}

function removeFence() {
  if (fenceEntities.length === 0) {
    console.log('没有围栏可以移除');
    return;
  }
  
  // 移除最后一个绘制的围栏（数组中的最后一个元素）
  const lastFence = fenceEntities.pop();
  cesiumMap.removeEntity(lastFence);
  
  // 更新fenceEntity引用
  if (fenceEntities.length > 0) {
    fenceEntity = fenceEntities[fenceEntities.length - 1];
  } else {
    fenceEntity = null;
  }
  
  console.log(`已移除围栏，剩余围栏数量: ${fenceEntities.length}`);
  fenceCount.value--;
}

function clearAllFences() {
  fenceEntities.forEach(fence => cesiumMap.removeEntity(fence));
  fenceEntities = [];
  fenceEntity = null;
  popupEnabled.value = true;
  fenceCount.value = 0;
}

function startDrawFence() {
  popupEnabled.value = false;
  clearDrawing();
  drawing = true;
  drawType = 'fence';
  cesiumMap.addScreenSpaceEventHandler(CesiumMap.ScreenSpaceEventType.LEFT_CLICK, handleDrawClick);
  cesiumMap.addScreenSpaceEventHandler(CesiumMap.ScreenSpaceEventType.MOUSE_MOVE, handleDrawMove);
  cesiumMap.addScreenSpaceEventHandler(CesiumMap.ScreenSpaceEventType.RIGHT_CLICK, handleDrawEnd);
}

function handleDrawClick(movement) {
  const cartesian = cesiumMap.viewer.scene.pickPosition(movement.position);
  if (!cartesian) return;
  const cartographic = CesiumMap.Cartographic.fromCartesian(cartesian);
  const lng = CesiumMap.Math.toDegrees(cartographic.longitude);
  const lat = CesiumMap.Math.toDegrees(cartographic.latitude);
  drawingPositions.push([lng, lat]);
  const pointEntity = cesiumMap.addEntity({
    position: CesiumMap.Cartesian3.fromDegrees(lng, lat),
    point: {
      pixelSize: 10,
      color: CesiumMap.Color.RED,
      outlineColor: CesiumMap.Color.WHITE,
      outlineWidth: 2
    }
  });
  drawPointEntities.push(pointEntity);
  if (drawType === 'circle' && drawingPositions.length === 2) {
    handleDrawEnd();
  }
}

function handleDrawMove(movement) {
  if (!drawing || drawingPositions.length === 0) return;
  let tempPositions = [...drawingPositions];
  let tempEntityOptions = {};
  if (drawType === 'polyline') {
    const cartesian = cesiumMap.viewer.scene.pickPosition(movement.endPosition);
    if (cartesian) {
      const cartographic = CesiumMap.Cartographic.fromCartesian(cartesian);
      tempPositions.push([
        CesiumMap.Math.toDegrees(cartographic.longitude),
        CesiumMap.Math.toDegrees(cartographic.latitude)
      ]);
    }
    tempEntityOptions = {
      positions: tempPositions,
      color: CesiumMap.Color.ORANGE,
      width: 3
    };
    if (drawingEntity) cesiumMap.removeEntity(drawingEntity);
    drawingEntity = cesiumMap.addPolyline(tempEntityOptions);
  } else if (drawType === 'circle') {
    if (drawingPositions.length === 1) {
      const cartesian = cesiumMap.viewer.scene.pickPosition(movement.endPosition);
      if (cartesian) {
        const cartographic = CesiumMap.Cartographic.fromCartesian(cartesian);
        const lng = CesiumMap.Math.toDegrees(cartographic.longitude);
        const lat = CesiumMap.Math.toDegrees(cartographic.latitude);
        const center = drawingPositions[0];
        const radius = CesiumMap.Cartesian3.distance(
          CesiumMap.Cartesian3.fromDegrees(center[0], center[1]),
          CesiumMap.Cartesian3.fromDegrees(lng, lat)
        );
        tempEntityOptions = {
          lon: center[0],
          lat: center[1],
          radius,
          color: CesiumMap.Color.ORANGE.withAlpha(0.3),
          outlineColor: CesiumMap.Color.ORANGE,
          outlineWidth: 2
        };
        if (drawingEntity) cesiumMap.removeEntity(drawingEntity);
        drawingEntity = cesiumMap.addCircle(tempEntityOptions);
      }
    }
  } else if (drawType === 'polygon') {
    const cartesian = cesiumMap.viewer.scene.pickPosition(movement.endPosition);
    if (cartesian) {
      const cartographic = CesiumMap.Cartographic.fromCartesian(cartesian);
      tempPositions.push([
        CesiumMap.Math.toDegrees(cartographic.longitude),
        CesiumMap.Math.toDegrees(cartographic.latitude)
      ]);
    }
    tempEntityOptions = {
      positions: tempPositions,
      color: CesiumMap.Color.ORANGE.withAlpha(0.3),
      outlineColor: CesiumMap.Color.ORANGE,
      outlineWidth: 2
    };
    if (drawingEntity) cesiumMap.removeEntity(drawingEntity);
    drawingEntity = cesiumMap.addPolygon(tempEntityOptions);
  } else if (drawType === 'fence') {
    const cartesian = cesiumMap.viewer.scene.pickPosition(movement.endPosition);
    if (cartesian) {
      const cartographic = CesiumMap.Cartographic.fromCartesian(cartesian);
      tempPositions.push([
        CesiumMap.Math.toDegrees(cartographic.longitude),
        CesiumMap.Math.toDegrees(cartographic.latitude)
      ]);
    }
    tempEntityOptions = {
      positions: tempPositions,
      height: 200,
      color: CesiumMap.Color.CYAN.withAlpha(0.5),
      outlineColor: CesiumMap.Color.CYAN,
      outlineWidth: 2
    };
    if (drawingEntity) cesiumMap.removeEntity(drawingEntity);
    drawingEntity = cesiumMap.addFence(tempEntityOptions);
  }
}

function handleDrawEnd() {
  if (!drawing) return;
  if (drawingEntity) cesiumMap.removeEntity(drawingEntity);
  if (drawType === 'polyline' && drawingPositions.length > 1) {
    polylineEntity = cesiumMap.addPolyline({
      positions: drawingPositions,
      color: CesiumMap.Color.ORANGE,
      width: 3
    });
  } else if (drawType === 'circle' && drawingPositions.length === 2) {
    const center = drawingPositions[0];
    const edge = drawingPositions[1];
    const radius = CesiumMap.Cartesian3.distance(
      CesiumMap.Cartesian3.fromDegrees(center[0], center[1]),
      CesiumMap.Cartesian3.fromDegrees(edge[0], edge[1])
    );
    circleEntity = cesiumMap.addCircle({
      lon: center[0],
      lat: center[1],
      radius,
      color: CesiumMap.Color.ORANGE.withAlpha(0.3),
      outlineColor: CesiumMap.Color.ORANGE,
      outlineWidth: 2
    });
  } else if (drawType === 'polygon' && drawingPositions.length > 2) {
    polygonEntity = cesiumMap.addPolygon({
      positions: drawingPositions,
      color: CesiumMap.Color.ORANGE.withAlpha(0.3),
      outlineColor: CesiumMap.Color.ORANGE,
      outlineWidth: 2
    });
  } else if (drawType === 'fence' && drawingPositions.length > 2) {
    const newFence = cesiumMap.addFence({
      positions: drawingPositions,
      height: 200,
      color: CesiumMap.Color.CYAN.withAlpha(0.5),
      outlineColor: CesiumMap.Color.CYAN,
      outlineWidth: 2
    });
    fenceEntities.push(newFence);
    fenceEntity = newFence;
    fenceCount.value++;
  }
  clearDrawing();
  popupEnabled.value = true;
}

function startMeasureDistance() {
  popupEnabled.value = false;
  clearMeasure();
  measureType = 'distance';
  measurePositions = [];
  measureResult.value = '';
  cesiumMap.addScreenSpaceEventHandler(CesiumMap.ScreenSpaceEventType.LEFT_CLICK, handleMeasureClick);
  cesiumMap.addScreenSpaceEventHandler(CesiumMap.ScreenSpaceEventType.MOUSE_MOVE, handleMeasureMove);
  cesiumMap.addScreenSpaceEventHandler(CesiumMap.ScreenSpaceEventType.RIGHT_CLICK, endMeasure);
}

function startMeasureArea() {
  popupEnabled.value = false;
  clearMeasure();
  measureType = 'area';
  measurePositions = [];
  measureResult.value = '';
  cesiumMap.addScreenSpaceEventHandler(CesiumMap.ScreenSpaceEventType.LEFT_CLICK, handleMeasureClick);
  cesiumMap.addScreenSpaceEventHandler(CesiumMap.ScreenSpaceEventType.MOUSE_MOVE, handleMeasureMove);
  cesiumMap.addScreenSpaceEventHandler(CesiumMap.ScreenSpaceEventType.RIGHT_CLICK, endMeasure);
}

function clearMeasure() {
  if (measureEntity) {
    cesiumMap.removeEntity(measureEntity);
    measureEntity = null;
  }
  measurePointEntities.forEach(e => cesiumMap.removeEntity(e));
  measurePointEntities = [];
  measurePositions = [];
  measureResult.value = '';
  cesiumMap.removeScreenSpaceEventHandler(CesiumMap.ScreenSpaceEventType.LEFT_CLICK);
  cesiumMap.removeScreenSpaceEventHandler(CesiumMap.ScreenSpaceEventType.MOUSE_MOVE);
  cesiumMap.removeScreenSpaceEventHandler(CesiumMap.ScreenSpaceEventType.RIGHT_CLICK);
  popupEnabled.value = true;
}

function handleMeasureClick(movement) {
  const cartesian = cesiumMap.viewer.scene.pickPosition(movement.position);
  if (!cartesian) return;
  const cartographic = CesiumMap.Cartographic.fromCartesian(cartesian);
  const lng = CesiumMap.Math.toDegrees(cartographic.longitude);
  const lat = CesiumMap.Math.toDegrees(cartographic.latitude);
  measurePositions.push([lng, lat]);
  const pointEntity = cesiumMap.addEntity({
    position: CesiumMap.Cartesian3.fromDegrees(lng, lat),
    point: {
      pixelSize: 10,
      color: CesiumMap.Color.RED,
      outlineColor: CesiumMap.Color.WHITE,
      outlineWidth: 2
    }
  });
  measurePointEntities.push(pointEntity);
}

function handleMeasureMove(movement) {
  if (!measureType || measurePositions.length === 0) return;
  let tempPositions = [...measurePositions];
  const cartesian = cesiumMap.viewer.scene.pickPosition(movement.endPosition);
  if (cartesian) {
    const cartographic = CesiumMap.Cartographic.fromCartesian(cartesian);
    tempPositions.push([
      CesiumMap.Math.toDegrees(cartographic.longitude),
      CesiumMap.Math.toDegrees(cartographic.latitude)
    ]);
  }
  if (measureEntity) cesiumMap.removeEntity(measureEntity);
  if (measureType === 'distance') {
    measureEntity = cesiumMap.addPolyline({
      positions: tempPositions,
      color: CesiumMap.Color.RED,
      width: 3
    });
    const len = CesiumMap.calcPolylineLength(tempPositions);
    measureResult.value = `距离：${len.toFixed(2)} 米`;
  } else if (measureType === 'area' && tempPositions.length > 2) {
    measureEntity = cesiumMap.addPolygon({
      positions: tempPositions,
      color: CesiumMap.Color.RED.withAlpha(0.3),
      outlineColor: CesiumMap.Color.RED,
      outlineWidth: 2
    });
    const area = CesiumMap.calcPolygonArea(tempPositions);
    measureResult.value = `面积：${area.toFixed(2)} 平方米`;
  }
}

function endMeasure() {
  if (measureEntity) cesiumMap.removeEntity(measureEntity);
  if (measureType === 'distance' && measurePositions.length > 1) {
    measureEntity = cesiumMap.addPolyline({
      positions: measurePositions,
      color: CesiumMap.Color.RED,
      width: 3
    });
    const len = CesiumMap.calcPolylineLength(measurePositions);
    measureResult.value = `距离：${len.toFixed(2)} 米`;
  } else if (measureType === 'area' && measurePositions.length > 2) {
    measureEntity = cesiumMap.addPolygon({
      positions: measurePositions,
      color: CesiumMap.Color.RED.withAlpha(0.3),
      outlineColor: CesiumMap.Color.RED,
      outlineWidth: 2
    });
    const area = CesiumMap.calcPolygonArea(measurePositions);
    measureResult.value = `面积：${area.toFixed(2)} 平方米`;
  }
  cesiumMap.removeScreenSpaceEventHandler(CesiumMap.ScreenSpaceEventType.LEFT_CLICK);
  cesiumMap.removeScreenSpaceEventHandler(CesiumMap.ScreenSpaceEventType.MOUSE_MOVE);
  cesiumMap.removeScreenSpaceEventHandler(CesiumMap.ScreenSpaceEventType.RIGHT_CLICK);
  measureType = '';
  measurePointEntities.forEach(e => cesiumMap.removeEntity(e));
  measurePointEntities = [];
  popupEnabled.value = true;
}

function addArc() {
  cesiumMap.addArc({
    center: [116.3913, 39.9075], // 圆心
    radius: 2000,                // 半径（米）
    startAngle: 0,               // 起始角度
    endAngle: 120,               // 终止角度
    color: CesiumMap.Color.PURPLE,
    width: 4,
    name: '示例弧形'
  });
}

function startDrawArc() {
  popupEnabled.value = false;
  clearArcDraw();
  arcDrawPoints = [];
  cesiumMap.addScreenSpaceEventHandler(CesiumMap.ScreenSpaceEventType.LEFT_CLICK, handleArcDrawClick);
  cesiumMap.addScreenSpaceEventHandler(CesiumMap.ScreenSpaceEventType.MOUSE_MOVE, handleArcDrawMove);
  cesiumMap.addScreenSpaceEventHandler(CesiumMap.ScreenSpaceEventType.RIGHT_CLICK, endDrawArc);
}

function clearArcDraw() {
  if (arcDrawEntity) {
    cesiumMap.removeEntity(arcDrawEntity);
    arcDrawEntity = null;
  }
  arcDrawPoints = [];
  arcDrawPointEntities.forEach(e => cesiumMap.removeEntity(e));
  arcDrawPointEntities = [];
  cesiumMap.removeScreenSpaceEventHandler(CesiumMap.ScreenSpaceEventType.LEFT_CLICK);
  cesiumMap.removeScreenSpaceEventHandler(CesiumMap.ScreenSpaceEventType.MOUSE_MOVE);
  cesiumMap.removeScreenSpaceEventHandler(CesiumMap.ScreenSpaceEventType.RIGHT_CLICK);
  popupEnabled.value = true;
}

function handleArcDrawClick(movement) {
  const cartesian = cesiumMap.viewer.scene.pickPosition(movement.position);
  if (!cartesian) return;
  const cartographic = CesiumMap.Cartographic.fromCartesian(cartesian);
  const lng = CesiumMap.Math.toDegrees(cartographic.longitude);
  const lat = CesiumMap.Math.toDegrees(cartographic.latitude);
  arcDrawPoints.push([lng, lat]);
  const pointEntity = cesiumMap.addEntity({
    position: CesiumMap.Cartesian3.fromDegrees(lng, lat),
    point: {
      pixelSize: 10,
      color: CesiumMap.Color.RED,
      outlineColor: CesiumMap.Color.WHITE,
      outlineWidth: 2
    }
  });
  arcDrawPointEntities.push(pointEntity);
  if (arcDrawPoints.length === 3) {
    endDrawArc();
  }
}

function handleArcDrawMove(movement) {
  if (arcDrawPoints.length === 0) return;
  let tempPoints = [...arcDrawPoints];
  const cartesian = cesiumMap.viewer.scene.pickPosition(movement.endPosition);
  if (cartesian) {
    const cartographic = CesiumMap.Cartographic.fromCartesian(cartesian);
    tempPoints.push([
      CesiumMap.Math.toDegrees(cartographic.longitude),
      CesiumMap.Math.toDegrees(cartographic.latitude)
    ]);
  }
  if (arcDrawEntity) cesiumMap.removeEntity(arcDrawEntity);
  if (tempPoints.length >= 2) {
    const arcParams = getArcParams(tempPoints);
    if (arcParams) {
      arcDrawEntity = cesiumMap.addArc(arcParams);
    }
  }
}

function endDrawArc() {
  if (arcDrawEntity) cesiumMap.removeEntity(arcDrawEntity);
  if (arcDrawPoints.length === 3) {
    const arcParams = getArcParams(arcDrawPoints);
    if (arcParams) {
      arcDrawEntity = cesiumMap.addArc(arcParams);
    }
  }
  cesiumMap.removeScreenSpaceEventHandler(CesiumMap.ScreenSpaceEventType.LEFT_CLICK);
  cesiumMap.removeScreenSpaceEventHandler(CesiumMap.ScreenSpaceEventType.MOUSE_MOVE);
  cesiumMap.removeScreenSpaceEventHandler(CesiumMap.ScreenSpaceEventType.RIGHT_CLICK);
  arcDrawPoints = [];
  arcDrawPointEntities.forEach(e => cesiumMap.removeEntity(e));
  arcDrawPointEntities = [];
  popupEnabled.value = true;
}

function getArcParams(points) {
  if (points.length < 2) return null;
  const [center, p1, p2] = points;
  const radius = CesiumMap.calcDistance(center, p1);
  function getAngle(center, p) {
    const angle = Math.atan2(p[1] - center[1], p[0] - center[0]) * 180 / Math.PI;
    return (angle + 360) % 360;
  }
  const startAngle = getAngle(center, p1);
  const endAngle = points.length === 3 ? getAngle(center, p2) : startAngle;
  return {
    center,
    radius,
    startAngle,
    endAngle,
    color: CesiumMap.Color.PURPLE,
    width: 4,
    name: '鼠标绘制弧形'
  };
}

// 开始标记点，注册鼠标点击事件
function startMarkPoint() {
  popupEnabled.value = false;
  marking = true;
  cesiumMap.addScreenSpaceEventHandler(CesiumMap.ScreenSpaceEventType.LEFT_CLICK, handleMarkPointClick);
}

// 鼠标点击地图时添加一个点实体
function handleMarkPointClick(movement) {
  if (!marking) return;
  const cartesian = cesiumMap.viewer.scene.pickPosition(movement.position);
  if (!cartesian) return;
  const cartographic = CesiumMap.Cartographic.fromCartesian(cartesian);
  const lng = CesiumMap.Math.toDegrees(cartographic.longitude);
  const lat = CesiumMap.Math.toDegrees(cartographic.latitude);
  const entity = cesiumMap.addEntity({
    position: CesiumMap.Cartesian3.fromDegrees(lng, lat),
    point: {
      pixelSize: 12,
      color: CesiumMap.Color.BLUE,
      outlineColor: CesiumMap.Color.WHITE,
      outlineWidth: 2
    }
  });
  markerPointEntities.push(entity);
}

// 停止标记点，移除鼠标点击事件
function stopMarkPoint() {
  marking = false;
  cesiumMap.removeScreenSpaceEventHandler(CesiumMap.ScreenSpaceEventType.LEFT_CLICK);
  popupEnabled.value = true;
}

// 清除所有已标记的点
function clearMarkPoints() {
  markerPointEntities.forEach(e => cesiumMap.removeEntity(e));
  markerPointEntities = [];
  popupEnabled.value = true;
}
</script>

<style scoped>
.cesium-map-demo {
  position: relative;
  width: 100%;
  height: 100%;
  margin: 0;
  padding: 0;
  overflow: hidden;
}
.map-container {
  position: absolute;
  left: 0; top: 0;
  width: 100%;
  height: 100%;
  margin: 0;
  z-index: 0;
}
.toolbar {
  position: absolute;
  top: 20px;
  left: 20px;
  z-index: 10;
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  background: rgba(255,255,255,0.9);
  border-radius: 8px;
  padding: 8px 12px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.15);
  backdrop-filter: blur(10px);
}
.toolbar button {
  margin: 0;
  padding: 6px 12px;
  border: none;
  background: #409eff;
  color: #fff;
  border-radius: 4px;
  cursor: pointer;
  font-size: 13px;
  transition: all 0.2s;
  white-space: nowrap;
}
.toolbar button:hover {
  background: #66b1ff;
  transform: translateY(-1px);
  box-shadow: 0 2px 4px rgba(0,0,0,0.2);
}
.measure-result {
  position: absolute;
  top: 80px;
  left: 20px;
  z-index: 20;
  background: #fffbe6;
  color: #d46b08;
  padding: 8px 16px;
  border-radius: 6px;
  font-size: 14px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.15);
  border: 1px solid #ffe58f;
}
.fence-info {
  position: absolute;
  top: 80px;
  left: 200px;
  z-index: 20;
  background: #fffbe6;
  color: #d46b08;
  padding: 8px 16px;
  border-radius: 6px;
  font-size: 14px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.15);
  border: 1px solid #ffe58f;
}
.popup {
  position: absolute;
  z-index: 100;
  min-width: 160px;
  background: #fff;
  border: 1px solid #d9d9d9;
  border-radius: 6px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.15);
  padding: 10px 16px;
  color: #333;
  font-size: 14px;
  pointer-events: auto;
  user-select: text;
}
</style> 